package com.gouaixin.bee.beeframework2.tool;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import com.gouaixin.bee.beeframework2.bean.BaseModel;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by Administrator on 2015/4/22.
 */
//根据Gps获取当前城市
public class CityUtil {

    public static  String getIP() {
        String IP = null;
        StringBuilder IPStringBuilder = new StringBuilder();
        try {
            Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaceEnumeration.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement();
                Enumeration<InetAddress> inetAddressEnumeration = networkInterface.getInetAddresses();
                while (inetAddressEnumeration.hasMoreElements()) {
                    InetAddress inetAddress = inetAddressEnumeration.nextElement();
                    if (!inetAddress.isLoopbackAddress()&&
                            !inetAddress.isLinkLocalAddress()&&
                            inetAddress.isSiteLocalAddress()) {
                        IPStringBuilder.append(inetAddress.getHostAddress().toString()+"\n");
                    }
                }
            }
        } catch (SocketException ex) {

        }

        IP = IPStringBuilder.toString();

        mLog.e("第二种获取ip:" + IP);
        return IP;
    }


    public static String getCityWithIp(String ip) {
        String ipaddress="";

        String url="";

        if(ip.equals("")) {
            ip = "117.89.35.58";
        }

//        url=weburl;


//        String weburl="http://apistore.baidu.com/microservice/iplookup?ip=117.89.35.58";
        String weburl="http://api.map.baidu.com/location/ip?ak=GkNCBcRz1cmpwfgjcjDrR7lq";

        mLog.e("weburl" + weburl);




        BaseModel.setCallBackLister(new BaseModel.CallBackLister() {
            @Override
            public String onCallBack(String url, String result) {
                return result;

            }
        });
        BaseModel.get(url);
        return ipaddress;
    }





    public static String getLocalIpAddress() {
        String ipaddress="";

        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        ipaddress=ipaddress+";"+ inetAddress.getHostAddress().toString();

                        mLog.e("本机ip:" + ipaddress);
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("WifiPreference IpAddress", ex.toString());
            mLog.e("出错啦：" + ex.toString());
        }
        return ipaddress;
    }




    public static String getCurrentCity() {

        return "";
    }

    /**
     * 判断GPS是否开启，若未开启，则进入GPS设置页面；设置完成后需用户手动回界面
     *
     * @return
     */
    public static void openGPSSettings(Context context) {
        //获取位置服务
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //若GPS未开启
        if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(context, "请开启GPS！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            context.startActivity(intent);
        }
    }


    /**
     * 判断GPS是否开启，若未开启，则进入GPS设置页面；设置完成后仍回原界面
     *
     * @param currentActivity
     * @return
     */
    public static void openGPSSettings(Activity currentActivity) {
        //获取位置服务
        LocationManager lm = (LocationManager) currentActivity.getSystemService(Context.LOCATION_SERVICE);
        //若GPS未开启
        if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(currentActivity, "请开启GPS！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            currentActivity.startActivityForResult(intent, 0); //此为设置完成后返回到获取界面
        }
    }

//    /**
//     * 使用高德定位获取经纬度，包括GPS获取，网络获取;
//     *
//     * @param context 上下文环境
//     * @param locationListener 位置监听实例
//     * @return HashMap<String,Location> 返回Location实例的HashMap，其中，GPS对应的Location实例对应的Key值为"gps",网络为"network";
//     */
//    public static Map<String,Location> getLocationObject(Context context,LocationListener locationListener){
//        Map<String,Location> lMap = new HashMap<String, Location>();
//
//        LocationManagerProxy    locationManager = LocationManagerProxy.getInstance(context);
//        for(final String provider : locationManager.getProviders(true)){
//
//            //GPS
//            if(LocationManagerProxy.GPS_PROVIDER.equals(provider) )  {
//
//                Location l =locationManager.getLastKnownLocation(provider);
//                if(null != l){
//                    lMap.put(GPS, l);
//                }
//                locationManager.requestLocationUpdates(provider,  mLocationUpdateMinTime, mLocationUpdateMinDistance,locationListener);
//                break;
//            }
//
//            //网络 定位服务开启
//            if(LocationManagerProxy.NETWORK_PROVIDER.equals(provider))  {
//
//                Location l =locationManager.getLastKnownLocation(provider);
//                if(null != l){
//                    lMap.put(NETWORK, l);
//                }
//                locationManager.requestLocationUpdates(provider,  mLocationUpdateMinTime, mLocationUpdateMinDistance,locationListener);
//                break;
//            }
//
//        }
//        return lMap;
//    }


    public static String getCity(Context context) {

        String murl = "http://api.map.baidu.com/geocoder/v2/?ak=GkNCBcRz1cmpwfgjcjDrR7lq&callback=renderReverse&output=json&pois=1&qq-pf-to=pcqq.c2c&location=35,114";

//        latitude=0.0;
//        longitude=0.0;

        String latAndlon = longitude + "," + latitude;
        String weburl = "http://api.map.baidu.com/geocoder/v2/?ak=GkNCBcRz1cmpwfgjcjDrR7lq&callback=renderReverse&output=json&pois=1&qq-pf-to=pcqq.c2c&location=";


        getLatandLon(context);
        String url = weburl + latAndlon;
        BaseModel.setCallBackLister(new BaseModel.CallBackLister() {
            @Override
            public String onCallBack(String url, String result) {
                mLog.e("经纬度转化：返回值=" + result);
                return url;
            }
        });
        BaseModel.get(url);


        return "";
    }

    private static double latitude = 0.0;//经度
    private static double longitude = 0.0;//纬度

    public static void getLatandLon(Context context) {
        mLog.e("进入getLatandLon");

//获取经纬度
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Location location = locationManager
                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                latitude = location.getLatitude(); //经度
                longitude = location.getLongitude(); //纬度
                mLog.e("111111Location changed : Lat: "
                        + location.getLatitude() + " Lng: "
                        + location.getLongitude());
            }
        } else {
            LocationListener locationListener = new LocationListener() {
                public void onLocationChanged(Location location) { //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
                    if (location != null) {
                        mLog.e("222222Location changed : Lat: "
                                + location.getLatitude() + " Lng: "
                                + location.getLongitude());
                    }
                }

                public void onProviderDisabled(String provider) {
// Provider被disable时触发此函数，比如GPS被关闭
                }

                public void onProviderEnabled(String provider) {
// Provider被enable时触发此函数，比如GPS被打开
                }

                public void onStatusChanged(String provider, int status, Bundle extras) {
// Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
                }
            };
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null) {
                latitude = location.getLatitude(); //经度
                longitude = location.getLongitude(); //纬度
                mLog.e("33333Location changed : Lat: "
                        + location.getLatitude() + " Lng: "
                        + location.getLongitude());
            }
        }


    }




}
